package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.dto.UserStatisticsDTO;
import com.sky.entity.Orders;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.WorkspaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.DishOverViewVO;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.SetmealOverViewVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class WorkspaceServiceImpl implements WorkspaceService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 根据时间段统计营业数据
     * @param begin 统计开始时间
     * @param end 统计结束时间
     * @return 包含营业数据的 BusinessDataVO 对象
     */
    public BusinessDataVO getBusinessData(LocalDateTime begin, LocalDateTime end) {
        /**
         * 营业额：当日已完成订单的总金额
         * 有效订单：当日已完成订单的数量
         * 订单完成率：有效订单数 / 总订单数
         * 平均客单价：营业额 / 有效订单数
         * 新增用户：当日新增用户的数量
         */

        // 指定 Map 的泛型类型
        Map<String, Object> map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);

        // 查询总订单数
        List<Map<String, Object>> orderNumList = orderMapper.getDailyOrder(begin, end, null);
        Integer totalOrderCount = getOrderCount(orderNumList);

        map.put("status", Orders.COMPLETED);

        // 营业额
        List<Map<String, Object>> turnoverList = orderMapper.getDailyTurnover(begin, end, Orders.COMPLETED);
        Double turnover = getTurnover(turnoverList);

        // 有效订单数
        List<Map<String, Object>> validOrderCountList = orderMapper.getDailyOrder(begin, end, Orders.COMPLETED);
        Integer validOrderCount = getOrderCount(validOrderCountList);

        Double unitPrice = 0.0;
        Double orderCompletionRate = 0.0;

        if (totalOrderCount != 0 && validOrderCount != 0) {
            // 订单完成率
            orderCompletionRate = (double) validOrderCount / totalOrderCount;
            // 平均客单价
            unitPrice = turnover / validOrderCount;
        }

        // 新增用户数
        List<UserStatisticsDTO> userStatisticsDTOList = userMapper.getDailyUserStats(map);
        Integer newUsers = userStatisticsDTOList.isEmpty() ? 0 :
                userStatisticsDTOList.get(0).getNewCount() != null ?
                        userStatisticsDTOList.get(0).getNewCount() : 0;

        return BusinessDataVO.builder()
                .turnover(turnover)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .unitPrice(unitPrice)
                .newUsers(newUsers)
                .build();
    }

    /**
     * 从营业额列表中提取营业额
     * @param turnoverList 营业额列表
     * @return 营业额
     */
    private Double getTurnover(List<Map<String, Object>> turnoverList) {
        if (turnoverList.isEmpty()) {
            return 0.0;
        }
        Map<String, Object> turnoverMap = turnoverList.get(0);
        Object value = turnoverMap.get("dailySum");
        if (value == null) {
            return 0.0;
        }
        if (value instanceof Double) {
            return (Double) value;
        } else if (value instanceof BigDecimal) {
            // 将 BigDecimal 类型转换为 Double
            return ((BigDecimal) value).doubleValue();
        } else {
            log.error("dailySum 类型不匹配，实际类型: {}", value.getClass().getName());
            return 0.0;
        }
    }



    /**
     * 查询订单管理数据
     *
     * @return
     */
    public OrderOverViewVO getOrderOverView() {
        Map<String, Object> map = new HashMap<>();
        map.put("begin", LocalDateTime.now().with(LocalTime.MIN));
        map.put("status", Orders.TO_BE_CONFIRMED);

        // 待接单
        List<Map<String, Object>> waitingOrdersList = orderMapper.getDailyOrder(LocalDateTime.now().with(LocalTime.MIN), LocalDateTime.now().with(LocalTime.MAX), Orders.TO_BE_CONFIRMED);
        int waitingOrders = getOrderCount(waitingOrdersList);

        // 待派送
        List<Map<String, Object>> deliveredOrdersList = orderMapper.getDailyOrder(LocalDateTime.now().with(LocalTime.MIN), LocalDateTime.now().with(LocalTime.MAX), Orders.CONFIRMED);
        int deliveredOrders = getOrderCount(deliveredOrdersList);

        // 已完成
        List<Map<String, Object>> completedOrdersList = orderMapper.getDailyOrder(LocalDateTime.now().with(LocalTime.MIN), LocalDateTime.now().with(LocalTime.MAX), Orders.COMPLETED);
        int completedOrders = getOrderCount(completedOrdersList);

        // 已取消
        List<Map<String, Object>> cancelledOrdersList = orderMapper.getDailyOrder(LocalDateTime.now().with(LocalTime.MIN), LocalDateTime.now().with(LocalTime.MAX), Orders.CANCELLED);
        int cancelledOrders = getOrderCount(cancelledOrdersList);

        // 全部订单
        List<Map<String, Object>> allOrdersList = orderMapper.getDailyOrder(LocalDateTime.now().with(LocalTime.MIN), LocalDateTime.now().with(LocalTime.MAX), null);
        int allOrders = getOrderCount(allOrdersList);

        return OrderOverViewVO.builder()
                .waitingOrders(waitingOrders)
                .deliveredOrders(deliveredOrders)
                .completedOrders(completedOrders)
                .cancelledOrders(cancelledOrders)
                .allOrders(allOrders)
                .build();
    }

    /**
     * 从订单列表中提取订单数量
     * @param orderList 订单列表
     * @return 订单数量
     */
    private int getOrderCount(List<Map<String, Object>> orderList) {
        int count = 0;
        if (!orderList.isEmpty()) {
            Map<String, Object> orderMap = orderList.get(0);
            Object value = orderMap.get("ordersNum");
            if (value != null) {
                if (value instanceof Integer) {
                    count = (Integer) value;
                } else if (value instanceof Long) {
                    // 处理 Long 类型
                    count = ((Long) value).intValue();
                } else {
                    // 记录日志，提示类型不匹配
                    log.error("ordersNum 类型不匹配，实际类型: {}", value.getClass().getName());
                }
            }
        }
        return count;
    }

    /**
     * 查询菜品总览
     *
     * @return
     */
    public DishOverViewVO getDishOverView() {
        Map map = new HashMap();
        map.put("status", StatusConstant.ENABLE);
        Integer sold = dishMapper.countByMap(map);

        map.put("status", StatusConstant.DISABLE);
        Integer discontinued = dishMapper.countByMap(map);

        return DishOverViewVO.builder()
                .sold(sold)
                .discontinued(discontinued)
                .build();
    }

    /**
     * 查询套餐总览
     *
     * @return
     */
    public SetmealOverViewVO getSetmealOverView() {
        Map map = new HashMap();
        map.put("status", StatusConstant.ENABLE);
        Integer sold = setmealMapper.countByMap(map);

        map.put("status", StatusConstant.DISABLE);
        Integer discontinued = setmealMapper.countByMap(map);

        return SetmealOverViewVO.builder()
                .sold(sold)
                .discontinued(discontinued)
                .build();
    }
}
